package com.hornsun.admin;

import com.alibaba.fastjson.JSONObject;
import com.hornsun.client.personalPage.service.HealthBeansService;
import com.hornsun.configInfo.ConfigInfo;
import com.hornsun.configInfo.WechatAPI;
import com.hornsun.database.IRedisService;
import com.hornsun.database.SerializeUtils;
import com.hornsun.database.WechatInfo;
import com.hornsun.domain.constant.error.AccountError;
import com.hornsun.domain.constant.types.HealthBeansSource;
import com.hornsun.domain.dbo.MemberWechat;
import com.hornsun.repository.AdministratorRepository;
import com.hornsun.repository.MemberWechatRepository;
import com.hornsun.util.CaptchaUtil;
import com.hornsun.util.SendHttpRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by 编译中... on 2018/4/8.
 */
@RestController
@RequestMapping("/admin")
public class Admin {
    @Resource
    private IRedisService service;

    @Resource
    private ConfigInfo configInfo;

    @Resource
    private WechatAPI wechatAPI;

    @Resource
    private MemberWechatRepository memberWechatRepository;

    @Resource
    private AdministratorRepository administratorRepository;

    @Resource
    private HealthBeansService healthBeansService;



    @Transactional
    @GetMapping("/wxLogin")
    public ResponseEntity<String> wxLogin(@RequestParam("code")String code){
        String param = "appid="+configInfo.getAppId()+"&secret="+configInfo.getSecret()+"&js_code="+code+"&grant_type=authorization_code";
        String result = SendHttpRequest.sendGet(wechatAPI.getLogin(),param);
        JSONObject jsStr = JSONObject.parseObject(result);
        String openid = jsStr.getString("openid");
        String sessionKey=jsStr.getString("session_key");
        String unionid = jsStr.getString("unionid");
        if (!memberWechatRepository.openidExist(openid)){
            MemberWechat memberWechat = new MemberWechat();
            memberWechat.setOpenid(openid);
            memberWechat.setUnionid(unionid);
            memberWechatRepository.insertMemberWechat(memberWechat);
            healthBeansService.gainHealthBeans(openid,configInfo.getFirstLogin(), HealthBeansSource.FIRSTLOGIN.getName());
        }
        String sessionid;
        if (service.isKeyExists(openid)){
            if(service.isOverdue(openid)){
                String oldSession = service.get(openid).toString();
                service.remove(openid);
                service.remove(oldSession);
                sessionid = UUID.randomUUID().toString();
                service.put(openid,sessionid,24*60*60);
                WechatInfo wechatInfo = new WechatInfo();
                wechatInfo.setOpenid(openid);
                wechatInfo.setSessionKey(sessionKey);
                if(unionid!=null){
                    wechatInfo.setUnionid(unionid);
                }
                service.put(sessionid,SerializeUtils.serialize(wechatInfo),24*60*60);
            }else {
                sessionid=service.get(openid).toString();
            }
        }else {
                sessionid = UUID.randomUUID().toString();
                service.put(openid,sessionid,24*60*60);
                WechatInfo wechatInfo = new WechatInfo();
                wechatInfo.setOpenid(openid);
                wechatInfo.setSessionKey(sessionKey);
                if(unionid!=null){
                    wechatInfo.setUnionid(unionid);
                }
                service.put(sessionid,SerializeUtils.serialize(wechatInfo),24*60*60);
        }
        return new ResponseEntity<String>(sessionid,HttpStatus.OK);
    }




    @PostMapping("/login")
    public ResponseEntity<?> login(HttpSession httpSession,
                                   @RequestParam("account")String account,
                                   @RequestParam("password")String password,
                                   @RequestParam("code")String code){
        String verificationCode = (String)httpSession.getAttribute("code");
        if (!(code.toUpperCase()).equals(verificationCode)){
            return new ResponseEntity<Object>(AccountError.VERIFICATION_CODE_ERROR.getCode(),HttpStatus.OK);
        }
        String account1 = (String)httpSession.getAttribute("account");
        if (StringUtils.isEmpty(account1)){
            if (administratorRepository.checkAccountInfo(account,password)){
                httpSession.setAttribute("account", account);
                return new ResponseEntity<Object>(account,HttpStatus.OK);
            }else {
                return new ResponseEntity<Object>(AccountError.ACCOUNT_OR_PASSWORD_ERROR.getCode(), HttpStatus.OK);
            }
        }
        return new ResponseEntity<Object>(account1,HttpStatus.OK);
    }


    @PostMapping("/logout")
    public ResponseEntity<?> logout(HttpSession httpSession) {
        httpSession.invalidate();
        return new ResponseEntity<Object>(HttpStatus.OK);
    }

    @GetMapping("/getVerification")
    public void getVerification(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 通知浏览器不要缓存
        response.setHeader("Expires", "-1");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "-1");
        CaptchaUtil util = CaptchaUtil.instance();
        // 将验证码输入到session中，用来验证
        String code = util.getString();
        request.getSession().setAttribute("code", code.toUpperCase());
        // 输出打web页面
        try {
            ImageIO.write(util.getImage(), "jpg", response.getOutputStream());
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}